package com.lzc.blog.handler;

import com.alibaba.fastjson.JSON;
import com.lzc.blog.dao.pojo.SysUser;
import com.lzc.blog.service.LoginService;
import com.lzc.blog.utils.UserThreadLocal;
import com.lzc.blog.vo.ErrorCode;
import com.lzc.blog.vo.Result;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在执行controller方法之前进行执行
        /**
         * 1.需要判断 请求的接口路径是否为 HandlerMethod（Controller 方法）
         * 2.判断token是否为空，如果为空 未登录
         * 3.如果token不为空，登录验证 loginService checkToken
         * 4.如果认证成功，放行即可
         */
        if (!(handler instanceof HandlerMethod)){
            //handler 可能是 RequestResourceHandler springboot程序 访问静态资源 默认去classpath下的static目录去查询
            return true;
        }
        String token=request.getHeader("Authorization");
        if (StringUtils.isEmptyOrWhitespaceOnly(token)){
            token=request.getHeader("Oauth-Token");
        }
        log.info("=================request start===========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}",requestURI);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");
        if (StringUtils.isEmptyOrWhitespaceOnly(token)){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        SysUser user = loginService.checkToken(token);
        if (user==null){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        //登录验证成功，放行
        //希望在controller中，直接获取用户的信息 怎么获取？
        UserThreadLocal.put(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 需要删除ThreadLocal中用完的信息，否则会有内存泄露的风险
        UserThreadLocal.remove();

    }
}
